//注意：不能在子组件里使用

import Taro, { Component, Config } from '@tarojs/taro'
import './index.scss'
import { View, ScrollView, Text, Button } from '@tarojs/components'
import { observer, inject } from '@tarojs/mobx'

import { IconFont } from '@components'

// 设定默认最大宽度
const systemInfo = Taro.getSystemInfoSync();
const deciveWidth = systemInfo.screenWidth - 20;

const { windowHeight, } = systemInfo

const tabInnerHeight = `${windowHeight}px`

//去掉所有的html标记
function delHtmlTag(str) {
    return str.replace(/<[^>]+>/g, "");//去掉所有的html标记
}
@inject('newsDetailStore') @inject('homeStore')
@observer
class Share extends Component {
    config: Config = {
        navigationBarTitleText: '分享海报'
    }
    constructor(props) {
        super(props)
        this.store = this.props.newsDetailStore;
        if ((this.$router.params).i) {
            var info = this.props.homeStore.fastNewsList[(this.$router.params).i].data[(this.$router.params).k];
            console.log(info);
            this.store.newsInfo = {
                title: info.title,
                content: info.content,
                timeStr: info.day + " " + info.time,
                weekday: info.weekday
            }
        }
        this.state = {
            imageTempPath: '',//海报缓存路径
            titleYHeight: '', // 标题高度
            contentYHeight: '', // 内容高度
            posterWidth: deciveWidth, //海报宽度
            posterHeight: 1000,//海报高度
            shareType: (this.$router.params).newsInfo ? 2 : 1, // 2为快讯 1为推荐文章
            title: '', //海报标题
            content: ''//海报内容
        }
    }
    componentWillMount() {
        this.drawBall();
    }

    componentWillReact() {

    }

    componentDidMount() {
        this.handlePosterHeight();

    }

    //小程序转发
    onShareAppMessage(res) {
        if (res.from === 'button') {
            // 来自页面内转发按钮
            console.log(res.target)
            // wechatFriends

            // return {
            //     title: this.store.newsInfo.title,
            //     path: `/pages/detail/index?newsId=${this.store.newsInfo.newsId}&type=1`
            // }
        }
        return {
            title: this.store.newsInfo.title,
            path: this.state.shareType == 2 ? '/pages/home/index' : `/pages/detail/index?newsId=${this.store.newsInfo.newsId}&type=1`
        }


    }

    handlePosterHeight = () => {
        let { titleYHeight, contentYHeight } = this.state
        //其他固定高度
        let otherHeight = 80
        this.setState({
            posterHeight: titleYHeight + contentYHeight - otherHeight
        })
    }



    drawBall() {
        const context = Taro.createCanvasContext('canvas', this)
        const _this = this;
        //logo宽高
        let logoWidth = 350 * 0.5;
        let logoHeight = 260 * 0.5;
        //二维吗 宽高
        let qrcodeWidth = deciveWidth - 40;
        let qrcodeHeight = (deciveWidth - 40) * 216 / 545;
        //底图背景
        context.setFillStyle('#ffffff')
        context.fillRect(0, 0, this.state.posterWidth, this.state.posterHeight)
        // Taro.getImageInfo({
        //     src: 'http://linqin.b0.upaiyun.com/Work/huoxingchuanmei/share_logo.jpg',
        // }).then((res) => {
        //     //logo
        //     context.drawImage(res.path, (deciveWidth - logoWidth)/2, 0, 350 * 0.5, 260 * 0.5);
        //     context.draw(true)
        // }

        // );


        // logo
        this.ImageInfo('https://api.marschinalink.com/files/upload/share_logo.jpg').then(data => {
            context.drawImage(data.path, (deciveWidth - logoWidth) / 2, 20, 350 * 0.5, 260 * 0.5);
            context.draw(true)
        })
        // 日期
        //context.drawImage(res2.path, 0, 150, 160, 120);
        context.setFontSize(14);
        context.setFillStyle('#666666');
        context.fillText(`${this.store.newsInfo.timeStr}   ${this.store.newsInfo.weekday}`, 20, logoHeight + 50);
        //标题
        context.font = 'normal 11px sans-serif';
        context.setFontSize(18);
        context.setFillStyle('#333333');
        this.fillTextWrap(context, this.store.newsInfo.title, 20, logoHeight + 80, null, 20, 4, (y) => {
            //得到 高度 给后面元素定位
            this.state.titleYHeight = y;
            this.setState({
                titleYHeight: y
            })

        });
        // 内容
        context.font = 'normal 11px sans-serif';
        context.setFontSize(16);
        context.setFillStyle('#666666');
        this.fillTextWrap(context, delHtmlTag(this.store.newsInfo.content), 20, this.state.titleYHeight + 10, null, 20, 10, (y) => {
            //得到 高度 给后面元素定位
            this.state.contentYHeight = y;
            this.setState({
                contentYHeight: y
            })
        });
        //context.draw(true)
        // Taro.getImageInfo({
        //     src: 'http://linqin.b0.upaiyun.com/Work/huoxingchuanmei/share_qrcode.jpg',
        // }).then((res) => {
        //     //qrcode
        //     context.drawImage(res.path, (deciveWidth - qrcodeWidth) / 2, this.state.contentYHeight + 10, qrcodeWidth, qrcodeHeight);
        //     context.draw(true)
        // }
        // );


        this.ImageInfo(`https://api.marschinalink.com/files/upload/share_qrcode.jpg`).then(data => {
            context.drawImage(data.path, (deciveWidth - qrcodeWidth) / 2, this.state.contentYHeight + 10, qrcodeWidth, qrcodeHeight);
            context.draw(true)
        })

    }

    // 获得canvas图片信息
    ImageInfo(path) {
        return new Promise((resolve, reject) => { // 采用异步Promise保证先获取到图片信息才进行渲染避免报错
            Taro.getImageInfo(
                {
                    src: path,
                    success: function (res) {
                        resolve(res)
                    },
                    fail: function (res) {
                        reject(res)
                    }
                }
            )
        })
    }

    // 点击保存图片生成微信临时模板文件path
    save() {
        const that = this
        setTimeout(() => {
            Taro.canvasToTempFilePath({ // 调用小程序API对canvas转换成图
                x: 0, // 开始截取的X轴
                y: 0, // 开始截取的Y轴
                width: this.state.posterWidth, // 开始截取宽度
                height: this.state.posterHeight,  // 开始截取高度
                // destWidth: 375,  // 截取后图片的宽度（避免图片过于模糊，建议2倍于截取宽度）
                // destHeight: 520, // 截取后图片的高度（避免图片过于模糊，建议2倍于截取宽度）
                canvasId: 'canvas', // 截取的canvas对象
                success: function (res) { // 转换成功生成临时链接并调用保存方法
                    that.saveImage(res.tempFilePath)
                },
                fail: function (res) {
                    console.log('绘制临时路径失败')
                }
            })
        }, 100) // 延时100做为点击缓冲，可以不用
    }




    // 保存图片
    saveImage(imgSrc) {
        Taro.getSetting({
            success() {
                Taro.authorize({
                    scope: 'scope.writePhotosAlbum', // 保存图片固定写法
                    success() {
                        // 图片保存到本地
                        Taro.saveImageToPhotosAlbum({
                            filePath: imgSrc, // 放入canvas生成的临时链接
                            success() {
                                Taro.showToast({
                                    title: '保存成功',
                                    icon: 'success',
                                    duration: 2000
                                })
                            }
                        })
                    },
                    fail() {
                        Taro.showToast({
                            title: '您点击了拒绝微信保存图片，再次保存图片需要您进行截屏哦',
                            icon: 'none',
                            duration: 3000
                        })
                    }
                })
            }
        })
    }


    // 文字换行
    fillTextWrap(ctx, text, x = 0, y, maxWidth, lineHeight, omit = 10, callback) {
        let textheight = ''
        // 设定默认最大宽度
        const systemInfo = Taro.getSystemInfoSync();
        //屏幕宽度减去 x 
        const deciveWidth = this.state.posterWidth - x * 2.5;
        // 默认参数
        maxWidth = maxWidth || deciveWidth;
        lineHeight = lineHeight || 20;
        //原始 y
        const originalY = y;
        // 校验参数
        if (typeof text !== 'string' || typeof x !== 'number' || typeof y !== 'number') {
            return;
        }
        // 字符串分割为数组
        const arrText = text.split('');
        // 当前字符串及宽度
        let currentText = '';
        let currentWidth;
        //字体大小颜色在外面定义
        // ctx.font = 'normal 11px sans-serif';
        //ctx.setFontSize(16);
        //ctx.setFillStyle('#3A3A3A');
        ctx.setTextAlign('justify');
        //let empty = [];
        for (let letter of arrText) {
            currentText += letter;
            currentWidth = ctx.measureText(currentText).width;
            if (currentWidth > maxWidth) {
                if (originalY + lineHeight * omit <= y) {
                    currentText = currentText.slice(0, -1) + '...'; //这里只显示指定行数，超出的用...表示
                    break;
                }
                ctx.fillText(currentText, x, y);
                currentText = '';
                y += lineHeight;


            }
        }

        if (currentText) {
            ctx.fillText(currentText, x, y);
        }
        //返回 Y 高度
        callback(y + lineHeight)
    }


    render() {
        const { newsDetailStore: { newsInfo } } = this.props

        return (
            <View className='container'>
                <ScrollView
                    className='share-scroll-view'
                    style={{ height: tabInnerHeight }}
                    scrollY

                >   <View className='share-wrap'>
                        <canvas style={`width: ${this.state.posterWidth}px ; height: ${this.state.posterHeight}px;`} canvas-id="canvas"></canvas>
                    </View>
                </ScrollView>
                <View className='share-footer-bar' >
                    <View className='share-footer-bar__button' onClick={this.save.bind(this)}>
                        <IconFont icon={'0xe600'} styles={{ fontSize: 36, color: '#666' }} />
                        <Text className='share-footer-bar__button-txt'>保存图片</Text>
                    </View>
                    <Button open-type="share" className='share-footer-bar__share-button' onClick={this.onShareAppMessage.bind(this)} >
                        <IconFont icon={'0xe684'} styles={{ fontSize: 36, color: '#666' }} />
                        <Text className='share-footer-bar__share-button-txt'>微信好友</Text>
                    </Button>
                </View>

            </View>
        )
    }
}
export default Share
